package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.zwy.gradetrack.entity.User;
import org.zwy.gradetrack.entity.UserRole;
import org.zwy.gradetrack.entity.Role;
import org.zwy.gradetrack.mapper.UserMapper;
import org.zwy.gradetrack.service.UserRoleService;
import org.zwy.gradetrack.service.UserService;
import org.zwy.gradetrack.service.RoleService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserRoleService userRoleService;
    private final RoleService roleService;

    @Autowired
    public UserServiceImpl(@Lazy UserRoleService userRoleService, RoleService roleService) {
        this.userRoleService = userRoleService;
        this.roleService = roleService;
    }

    @Override
    public IPage<User> pageUsers(Integer current, Integer size, String query, Long roleId) {
        Page<User> page = new Page<>(current, size);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(query)) {
            wrapper.like(User::getUsername, query)
                   .or()
                   .like(User::getRealName, query);
        }

        IPage<User> userPage = this.page(page, wrapper);

        if (roleId != null) {
            List<Long> userIdsWithRole = userRoleService.lambdaQuery()
                    .eq(UserRole::getRoleId, roleId)
                    .list()
                    .stream()
                    .map(UserRole::getUserId)
                    .collect(Collectors.toList());
            
            if (!userIdsWithRole.isEmpty()) {
                userPage.setRecords(userPage.getRecords().stream()
                        .filter(user -> userIdsWithRole.contains(user.getId()))
                        .collect(Collectors.toList()));
                userPage.setTotal(userPage.getRecords().size());
            } else {
                userPage.setRecords(List.of());
                userPage.setTotal(0);
            }
        }

        userPage.getRecords().forEach(user -> {
            List<UserRole> userRoles = userRoleService.getUserRoles(user.getId());
            List<Role> roles = userRoles.stream()
                    .map(userRole -> roleService.getById(userRole.getRoleId()))
                    .collect(Collectors.toList());
            user.setRoles(roles);
        });

        return userPage;
    }

    @Override
    @Transactional
    public boolean assignRoles(Long userId, List<Long> roleIds) {
        // 移除用户现有角色
        userRoleService.lambdaUpdate().eq(UserRole::getUserId, userId).remove();

        // 添加新角色
        if (roleIds != null && !roleIds.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            List<UserRole> userRoles = roleIds.stream()
                    .map(roleId -> {
                        UserRole userRole = new UserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        userRole.setCreateTime(now);
                        userRole.setUpdateTime(now);
                        return userRole;
                    })
                    .collect(Collectors.toList());
            return userRoleService.saveBatch(userRoles);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean removeRoles(Long userId, List<Long> roleIds) {
        if (roleIds != null && !roleIds.isEmpty()) {
            return userRoleService.lambdaUpdate()
                    .eq(UserRole::getUserId, userId)
                    .in(UserRole::getRoleId, roleIds)
                    .remove();
        }
        return false;
    }

    @Override
    public List<User> getUsersByRoleId(Long roleId) {
        List<Long> userIds = userRoleService.lambdaQuery()
                .eq(UserRole::getRoleId, roleId)
                .list()
                .stream()
                .map(UserRole::getUserId)
                .collect(Collectors.toList());
        
        if (!userIds.isEmpty()) {
            return this.listByIds(userIds);
        }
        return List.of();
    }
} 